package com.adgroup.smartnote;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import JsonModel.User;
import Net.JsonParse;
import Utilities.Configuration;
import Utilities.Utility;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.google.android.gms.gcm.GoogleCloudMessaging;

import database.Database;

public class LoginActivity extends SherlockActivity{

	EditText etEmail, etPassword;
	Button btnLogin;
	String gcmId = "";
	GoogleCloudMessaging gcm;
	TextView tvForgetPass;
	Button btnRegiset;
	Handler handler = new Handler();
	ActionBar mActionBar;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.menulogin, menu);
		return super.onCreateOptionsMenu(menu);
		
	}
	@Override
	public boolean onOptionsItemSelected(
			com.actionbarsherlock.view.MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menuSearchLogin:
			
			break;
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		//action bar
		mActionBar = getSupportActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(false);
		mActionBar.setDisplayUseLogoEnabled(true);
		mActionBar.setHomeButtonEnabled(true);
		mActionBar.setTitle(getResources().getString(R.string.buttonlogin));
		
		//mapping
		etEmail = (EditText) findViewById(R.id.editTextEmailLogin);
		etPassword = (EditText) findViewById(R.id.editTextPasswordLogin);
		btnLogin = (Button) findViewById(R.id.buttonLogin);
		tvForgetPass = (TextView) findViewById(R.id.textViewForgetPassword);
		btnRegiset = (Button) findViewById(R.id.buttonregisetinlogin);
		
		//forget pass word
		tvForgetPass.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(LoginActivity.this, ForgetPasswordActivity.class);
				startActivity(i);
			}
		});
		
		//register
		btnRegiset.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
				startActivityForResult(i, 903);
			}
		});
		
		//get gcm
		new AsynGetGCM().execute();
		btnLogin.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String  gmail = etEmail.getText().toString();
				String pass = (etPassword.getText().toString());
				//check infor
				if(gmail.equalsIgnoreCase("")){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.errornullgmailregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									ShowKeyboard(etEmail);
								}
					}).show();
				}
				else if(!Utility.isEmailValid(gmail)){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.errorninvalidgmailregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									ShowKeyboard(etEmail);
								}
					}).show();
				}
				else if(pass.equalsIgnoreCase("")){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.errornullpassregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									ShowKeyboard(etPassword);
								}
					}).show();
				}
				else if(pass.length()<6){
					new AlertDialog.Builder(LoginActivity.this)
					.setTitle(getResources().getString(R.string.errortitlelogin))
					.setMessage(getResources().getString(R.string.error6passregister))
					.setPositiveButton(getResources().getString(R.string.ok),
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									ShowKeyboard(etPassword);
								}
					}).show();
				}
				else{
					if(!Utility.isConnect(LoginActivity.this)){
						new AlertDialog.Builder(LoginActivity.this)
						.setTitle(getResources().getString(R.string.titleerrornetwork))
						.setMessage(getResources().getString(R.string.messageerrornetwork))
						.setNegativeButton(getResources().getString(R.string.setting), new DialogInterface.OnClickListener() {
							
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								
							}
						})
						.setPositiveButton(getResources().getString(R.string.cancel),
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int which) {
									}
						}).show();
					}
					else{
						pass = Utility.md5(pass);
						String[] params = new String[] {gmail,pass,gcmId,"0"};
						new AsyntaskLogin().execute(params);
					}
				}
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==903 && resultCode==RESULT_OK){//register then login
			Log.d("log","return");
			progress = ProgressDialog.show(LoginActivity.this, "",
					getResources().getString(R.string.logining), true);
			handler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					progress.dismiss();
					Intent returnIntent = new Intent();
					returnIntent.putExtra("result", data.getStringExtra("result"));
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			}, 1000);			
		}
	}
	//get gcm id
	class AsynGetGCM extends AsyncTask<Void, Void, Void>
	{

		@Override
		protected Void doInBackground(Void... params) {
			gcm = GoogleCloudMessaging.getInstance(LoginActivity.this);
			try {
				gcmId = gcm.register(Configuration.SENDERID);
				Log.d("log","gcm:"+gcmId);
			} catch (IOException e) {
				gcmId = "";
				Log.e("error",e.getMessage());
			}
			return null;
		}
		
	}
	
	private ProgressDialog progress;
	//asyntask login
	class AsyntaskLogin extends AsyncTask<String, Void, String>
	{
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			progress = ProgressDialog.show(LoginActivity.this, "",
					getResources().getString(R.string.logining), true);
		}
		@Override
		protected String doInBackground(String... params) {
			return new JsonParse().loginAccount(params,LoginActivity.this);
		}
		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			progress.dismiss();
			try {
				JSONObject json = new JSONObject(result);
				String r = json.getString(Configuration.result);
				if(r.equalsIgnoreCase(Configuration.norow)){
					Utility.ShowAlert(LoginActivity.this, getResources().getString(R.string.errortitlelogin), getResources().getString(R.string.errormessagelogin));
				}
				else{
					JSONObject rjson = json.getJSONArray(Configuration.result).getJSONObject(0);
					String gmai = rjson.getString(User.keyGmail);
					String nickname = rjson.getString(User.keyNickName);
					String birthday = rjson.getString(User.keyBirthday);
					String type = rjson.getString(User.keyType);
					String gender = rjson.getString(User.keyGender);
					String link = rjson.getString(User.keyLink);
					String userid = rjson.getString(User.keyUserId);
					User u = new User(userid, nickname, gender, birthday, link, type, gmai);
					new Database(LoginActivity.this).setUser(u);
					Intent returnIntent = new Intent();
					returnIntent.putExtra("result", nickname);
					returnIntent.putExtra("userid", userid);	
					
					setResult(RESULT_OK, returnIntent);
					finish();
				}
			} catch (JSONException e) {
				Log.e("error",e.getMessage());
				e.printStackTrace();
			}
			
			//Intent returnIntent = new Intent();
			//returnIntent.putExtra("result", etnickname.getText().toString());
			//setResult(RESULT_OK, returnIntent);
			//finish();
		}
	}
	//show keyboard
	public void ShowKeyboard(EditText et)
	{
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
	}
}
